using System;
using System.Collections;
using System.Reflection;
using DataLayer;

namespace BussinesLayerLogicTier
{
	/// <summary>
	/// Summary description for DataObject.
	/// </summary>
	public abstract class DataObject
	{
		private Hashtable loadKeys = new Hashtable();
		private ReloadType reloadType;
		
		public void UpdateLoadKeys()
		{
			//Generate LoadKeys each time the object is created
			
			LoadKeys.Clear();
			
			foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly))
			{
				foreach (FieldAttribute fa in pi.GetCustomAttributes(typeof(FieldAttribute),false))
				{
					if (fa.PrimaryKey)
					{
						LoadKeys.Add(fa.Name,pi.GetValue(this,null));		
					}
				}
			}
		}
		
		public static Hashtable LoadAllKeys(DataObject obj)
		{
			Hashtable keys = new Hashtable();
			keys.Clear();
			
			foreach (PropertyInfo pi in obj.GetType().GetProperties())
			{
				foreach (FieldAttribute fa in pi.GetCustomAttributes(typeof(FieldAttribute),false))
				{
					if (fa.PrimaryKey)
					{
						keys.Add(fa.Name,pi.GetValue(obj,null));		
					}
				}
			}
			return keys;
		}

		public Hashtable LoadKeys
		{
			get
			{
				if ( loadKeys == null )
					loadKeys = new Hashtable();
				return loadKeys ;
			}
			set
			{
				loadKeys = value;
			}
		}

		public ReloadType ReloadType
		{
			get { return reloadType; }
			set { reloadType = value; }
		}
		
		protected string TableName
		{
			get
			{
				TableAttribute[] tas = GetType().GetCustomAttributes(typeof (TableAttribute), true) as TableAttribute[];
				if ( tas.Length > 0 )
					return tas[0].Name;
				
				return string.Empty;
			}
		}
	}
}
